<template v-if="!isGoOther">
  <div class="user-list">
    <div class="" style="height:70px;" v-show="canShow"></div>
    <div class="authority-title">
      <h2>用户管理</h2>
      <svg class="all-close-btn icon-svg" v-show="!fullScreen" @click="closeAll" viewBox="0 0 612 792">
        <path :d="svgPath.closeFullScreen"/>
      </svg>
    </div>
    <!-- 表格主体 -->
    <div class="authority-content">
      <!-- 头部筛选 -->
      <div class="authority-search role-list-search">
        <div class="search-title"><img class='authority-icon' src="../../assets/img/search.png">筛选查询</div>
        <ul class="search-wrapper">
          <li>
            <span>输入搜索：</span>
            <input class="dap-input" type="text" maxlength="20" placeholder="输入用户账号/姓名" v-model="searchUserName">
          </li>
          <li>
            <span>所属部门：</span>
            <single-list-filter-without-cb ref="refListDept"
                                           @confirmSingleSelect="selectListDept"></single-list-filter-without-cb>
          </li>
          <li>
            <span class="dap-button" @click="getUser">查询</span>
          </li>
        </ul>
      </div>
      <!-- 表格 -->
      <div class="dap-table">
        <ul class="table-head">
          <li><img class='authority-icon' src="../../assets/img/user-list-icon.png">用户列表</li>
          <li><span class="dap-button" @click="addUserFun" v-if="perminsStrlist.permission_30013">添加</span></li>
        </ul>
        <div class="table-list">
          <el-table
            :data="tableData"
            v-loading="loadingShow"
            element-loading-text="loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"
            height="10">
            <el-table-column
              prop="number"
              label="序号"
              width="60px">
            </el-table-column>
            <el-table-column
              prop="loginName"
              label="用户账号"
              align="center">
            </el-table-column>
            <el-table-column
              prop="userName"
              label="姓名"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="sexText"
              label="性别"
              width="60px"
              align="center">
            </el-table-column>
            <el-table-column
              prop="filterJobName"
              label="职位"
              align="center">
            </el-table-column>
            <el-table-column
              label="所属部门"
              min-width="125px"
              align="center">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.depName.length>7" class="tab-item" effect="dark" :content=scope.row.depName
                            placement="top">
                  <span>{{scope.row.filterDepName}}</span>
                </el-tooltip>
                <span v-else>{{scope.row.depName}}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="所属单位"
              min-width="120"
              align="center">
              <template slot-scope="scope">
                <el-tooltip class="tab-item" effect="dark" :content=scope.row.unitName placement="top">
                  <span>{{scope.row.filterUnitName}}</span>
                </el-tooltip>
              </template>
            </el-table-column>

            <el-table-column
              prop="updateDate"
              label="更新时间"
              width="88px"
              align="center">
            </el-table-column>
            <el-table-column
              label="是否启用"
              align="center" v-if="perminsStrlist.permission_30014">
              <template slot-scope="scope">
                <el-switch
                  @change="isRunChange(scope.row)"
                  v-model=scope.row.isRun
                  active-color="#13ce66"
                  inactive-color="#ff4642">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              min-width="260px"
              v-if="(perminsStrlist.permission_30015 || perminsStrlist.permission_30016 || perminsStrlist.permission_30017)"
            >
              <template slot-scope="scope">
                <el-button v-if="perminsStrlist.permission_30015" @click="roleSetting(scope.row)" type="text"
                           size="small">角色权限设置
                </el-button>
                <el-button v-if="perminsStrlist.permission_30016" @click="editRole(scope.row)" type="text" size="small">
                  编辑
                </el-button>
                <el-button v-if="perminsStrlist.permission_30017" @click="delRole(scope.row)" type="text"
                           :class="{delBtn:!scope.row.isRun}" size="small"
                           :disabled="scope.row.isRun">删除
                </el-button>
                <el-button v-if="perminsStrlist.permission_30018" @click="updatePassword(scope.row)" type="text"
                           size="small">重置密码
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 分页 -->
      <dap-page :pageTotal="pageTotal" v-on:pageSizeChange="pageSizeChange"
                v-on:pageCurrentChange="pageCurrentChange" :currentPage="page"></dap-page>
    </div>
    <!-- 添加，编辑用户弹窗 -->
    <dap-popover ref="refDapPopover" :titleText="addTextPopover" :leftBtnText="'保存'" @clickLeft="saveBtnFun">
      <ul class="add-user-wrapper">
        <li>
          <div class="add-user-item">
            <i class="red-star">*</i><span class="add-text">用户账号：</span>
            <input type="text" :disabled="Boolean(userId)" v-model="addUserNumber" class="dap-input"
                   :class="{'error-input-border':!erroUserNumber,'disabled-inp':Boolean(userId)}"
                   placeholder="请输入字母或字母加数字组合" maxlength="20">
          </div>
          <p class="tip-text"><span v-show="!erroUserNumber">{{errUserNumberText}}</span></p>
        </li>
        <li>
          <div class="add-user-item">
            <i class="red-star">*</i><span class="add-text">姓名：</span>
            <input type="text" v-model="addUserName" class="dap-input" :class="{'error-input-border':!erroUserName}"
                   placeholder="最多输入20个汉字" maxlength="20">
          </div>
          <p class="tip-text"><span v-show="!erroUserName">{{errUserNameText}}</span></p>
        </li>
        <li>
          <div class="add-user-item">
            <i class="red-star">*</i><span class="add-text">性别：</span>
            <el-radio-group v-model="sex" size="mini">
              <el-radio label="1" border>男</el-radio>
              <el-radio label="0" border>女</el-radio>
            </el-radio-group>
          </div>
          <p class="tip-text" style="height:20px;"></p>
        </li>
        <li>
          <div class="add-user-item">
            <i class="red-star">*</i><span class="add-text">所属单位：</span>
            <p style="color:#969ca5">{{unitsName}}</p>
          </div>
          <p class="tip-text"></p>
        </li>
        <li>
          <div class="add-user-item">
            <i class="red-star">*</i><span class="add-text">所属部门：</span>
            <single-list-filter-without-cb ref="refDepts"
                                           @confirmSingleSelect="selectDept"></single-list-filter-without-cb>
          </div>
          <p class="tip-text"></p>
        </li>
        <li>
          <div class="add-user-item">
            <i class="red-star">*</i><span class="add-text">职位：</span>
            <single-list-filter-without-cb ref="refJobs"
                                           @confirmSingleSelect="selectJobs"></single-list-filter-without-cb>
          </div>
          <p class="tip-text"></p>
        </li>
      </ul>
    </dap-popover>
    <!-- 删除用户弹窗 -->
    <dap-popover ref="refDelePopover" @clickLeft='delBtnFun'>
      <p class="popover-text">您确认删除该用户吗？</p>
    </dap-popover>
    <!-- 重置密码弹窗 -->
    <dap-popover ref="refupdatePasswordPopover" @clickLeft="updateBtnFun">
      <p class="popover-text">您确认重置{{updateUserName}}的登录密码？</p>
    </dap-popover>
    <!-- 管理员禁用自己弹窗 -->
    <dap-popover ref="refIsRunPopover" @clickLeft="disableBtnFun" @clickRight="closeBtnFun">
      <p class="popover-text">确定要禁用自己吗？</p>
    </dap-popover>
  </div>
</template>
<script>

  import { svgPath, quitFullScreen } from "../../assets/js/utils";
  // 分页
  import dapPage from "../view/dap-page.vue";
  // 弹出窗
  import dapPopover from "../view/dap-popover.vue";
  // 下拉框
  import SingleListFilterWithoutCb from "../last/filter/single-list-filter-without-checkbox";
  // 请求axios文件,
  import {
    getUserList,               // 获取用户列表
    getListDept,                // 获取列表头部所属部门
    updateIsRun,               // 停用启用
    filterLogText,             // 字符太长过滤
    getUnitDeptJob,            // 添加用户时请求所有部门职位等
    addUser,                    // 添加用户
    updateUser,                // 编辑用户
    updatePwd,                // 重置密码
    delUser,                  // 删除用户
    logout                   // 注销
  } from "../../api/authority.js";

  export default {
    props: ["isChange", "fullScreen", 'pageChange'],
    data() {
      return {
        loadingShow: true,                 // loading
        addTextPopover: "添加用户",      // 添加和编辑头部文案
        userInfo: "",                    // 本地用户信息
        perminsStrlist: "",               // 用户所有权限列表
        svgPath: svgPath,
        canShow: true,
        searchUserName: "",       // 查询输入用户名或账号
        listDept: [],              // 查询所属部门
        searchDeptId: "",         // 查询输入部门
        updateUserName: "",       // 重置密码时用户名
        pageTotal: 0,             // 列表总条数
        tableData: [],           // 列表内容
        page: 1,                  // 页数
        pageSize: 20,              // 每页显示多少条
        user: "",                  // 操作时的用户信息

        erroUserName: false,      // 添加按钮判断用户姓名是否输入框合法
        erroUserNumber: false,    // 添加按钮判断用户账号是否输入框合法
        errUserNumberText: "",     // 添加时错误文案
        errUserNameText: "",       // 添加时错误文案
        userId: "",                //  编辑时用户id
        addUserNumber: "",        //  添加时用户账号
        addUserName: "",          //  添加时用户姓名
        unitDeptJob: "",          //  添加时所有的职位，部门信息
        unitsName: "",            //  添加时所属单位名称
        depts: [],                //  添加时所有部门
        jobs: [],                 //  添加时所有职位
        sex: "1",                //  性别
        deptId: "",               //   添加部门id
        jobsId: "",               //   添加职位id
        upDatedepName: "",         // 编辑时保留用户部门
        upDatejobName: "" ,            // 编辑时保留用户单位
        isGoOther:false,
      };
    },
    components: {
      dapPage,               // 分页
      dapPopover,            // 弹出窗
      SingleListFilterWithoutCb      // 下拉框
    },
    watch: {
      isChange() {
        if (document.querySelector(".el-header")) {
          this.canShow = true;
        } else {
          this.canShow = false;
        }
      },
      pageChange(){
        this.isGoOther = true;
        this.isGoOther = false;
        this.page = 1;
        this.pageSize = 20;
        this.initFun();
      }
    },
    activated() {
      if (!this.$route.query.roleSet) {
        this.initFun();
      }
    },
    mounted(){
      this.initFun();
    },
    methods: {
      // 初始化数据
      initFun() {
        this.searchUserName = "";
        this.userInfo = window.sessionStorage.getItem("sessionUser");
        if (this.userInfo) {
          this.userInfo = JSON.parse(this.userInfo);
        }
        this.perminsStrlist = this.userInfo.perminsStrlist;
        // 请求用户列表
        this.getUser();
        // 获取所属部门
        getListDept().then((res) => {
          if (res.code === 0) {
            this.listDept = [];
            this.listDept.push({ selectId: "", selectName: "全部" });
            res.data.forEach((item, ind) => {
              this.listDept.push({ selectId: item.deptId, selectName: item.deptName });
            });
            // 初始化所属部门下拉框中的数据refListDept
            this.$refs.refListDept.setSingleListData(this.listDept);
          }
        });
      },
      // 请求用户列表
      getUser() {
        this.loadingShow = true;
        getUserList({
          userName: this.searchUserName,
          depId: this.searchDeptId
        }, this.page, this.pageSize).then((data) => {
          if (data.code === 0) {
            data = data.data;
            this.tableData = data.list;
            this.pageTotal = data.total;
            data.list.forEach((item, ind) => {
              item.number = this.page * this.pageSize - this.pageSize + ind + 1;

              item.sexText = item.sex == 1 ? "男" : "女";
              item.isRun = Boolean(item.isRun);
              // 不超过7个字长度
              item.filterDepName = filterLogText(item.depName);
              item.filterUnitName = filterLogText(item.unitName);
              item.filterJobName = filterLogText(item.jobName);
            });
          } else {
            this.tableData = "";
          }
          this.loadingShow = false;
        }).catch(() => {
          this.loadingShow = false;
        });
      },
      // 停用启用
      isRunChange(user) {
        this.user = user;
        if ((!user.isRun) && (user.userId == this.userInfo.userId)) {
          this.$refs.refIsRunPopover.show();
        } else {
          this.axiosIsRun();
        }
      },

      // 用户自己操作自己时type为1，其他为空
      axiosIsRun(type = "") {
        this.$refs.refIsRunPopover.hide();
        updateIsRun(this.user.userId, Number(this.user.isRun)).then((res) => {
          if ((res.code === 0) && (type == 1)) {
            logout();
            window.sessionStorage.removeItem("sessionUser");
            location.href = "#/";
          }
          if (res.code !== 0) {
            // 如果请求失败保留原来停用启用状态
            this.user.isRun = !this.user.isRun;
          }
        }).catch(() => {
          this.user.isRun = !this.user.isRun;
        });
      },
      // 添加按钮
      addUserFun() {
        this.addTextPopover = "添加用户";
        this.sex = "1";
        this.userId = "";
        this.addUserNumber = "";
        this.addUserName = "";
        this.erroUserNumber = true;
        this.erroUserName = true;

        this.getUnitDeptJob();
        this.$refs.refDapPopover.show();
      },
      // 先所有获取部门，职位等信息 type  传1为编辑 可为空
      getUnitDeptJob(type = "") {
        getUnitDeptJob().then((res) => {
          if (res.code === 0) {
            this.unitDeptJob = res.data;
            this.unitsName = this.unitDeptJob.units[0].dictName;

            // 所属部门下拉
            this.deptId = this.unitDeptJob.depts[0].dictId;
            this.depts = [];
            this.unitDeptJob.depts.forEach((item) => {
              this.depts.push({ selectId: item.dictId, selectName: item.dictName });
            });
            this.$refs.refDepts.setSingleListData(this.depts);
            if (type == 1) {
              let ind = this.getArrIndex(this.depts, "selectName", this.upDatedepName);
              if (ind != -1) {
                this.$refs.refDepts.setCurrentSelectPosition(ind);
              }
            }

            // 职位下拉
            this.jobsId = this.unitDeptJob.depts[0].dictId;
            this.jobs = [];
            this.unitDeptJob.jobs.forEach((item) => {
              this.jobs.push({ selectId: item.dictId, selectName: item.dictName });
            });
            this.$refs.refJobs.setSingleListData(this.jobs);
            this.jobsId = this.jobs[0].selectId;
            if (type == 1) {
              let ind = this.getArrIndex(this.jobs, "selectName", this.upDatejobName);
              if (ind != -1) {
                this.$refs.refJobs.setCurrentSelectPosition(ind);
              }
            }
          }
        });
      },
      // 添加弹窗保存按钮
      saveBtnFun() {
        this.addUserNumber = this.addUserNumber.trim();
        this.addUserName = this.addUserName.trim();
        let regUserNumber = /^(\d*)([a-zA-Z]+)(\d*){1,20}$/;
        let regUserName = /^[\u4e00-\u9fa5]{1,20}$/;
        if (!this.addUserName) {
          this.erroUserName = false;
          this.errUserNameText = "姓名不能为空";
        } else if (!regUserName.test(this.addUserName)) {
          this.erroUserName = false;
          this.errUserNameText = "姓名格式不正确";
        } else {
          this.erroUserName = true;
        }
        if (!this.addUserNumber) {
          this.erroUserNumber = false;
          this.errUserNumberText = "用户账号不能为空";
        } else if (!regUserNumber.test(this.addUserNumber)) {
          this.erroUserNumber = false;
          this.errUserNumberText = "用户账号格式不正确";
        } else {
          this.erroUserNumber = true;
        }

        if (this.erroUserNumber && this.erroUserName) {
          if (this.userId) {
            let reqData = {
              userId: this.userId,
              userName: this.addUserName,
              sex: this.sex,
              dictJobId: this.jobsId,
              deptId: this.deptId,
              dictUnitId: this.unitDeptJob.units[0].dictId
            };
            updateUser(reqData).then((res) => {
              if (res.code === 0) {
                this.$message({
                  message: "用户编辑成功！",
                  center: true,
                  type: "success"
                });
                this.$refs.refDapPopover.hide();
                this.page = 1;
                this.getUser();
              } else {
                this.erroUserNumber = false;
                this.errUserNumberText = res.message;
              }
            });
          } else {
            let reqData = {
              userId: this.userId,
              userName: this.addUserName,
              loginName: this.addUserNumber,
              sex: this.sex,
              dictJobId: this.jobsId,
              deptId: this.deptId,
              dictUnitId: this.unitDeptJob.units[0].dictId
            };
            addUser(reqData).then((res) => {
              if (res.code === 0) {
                this.$message({
                  message: "用户创建成功！",
                  center: true,
                  type: "success"
                });
                this.$refs.refDapPopover.hide();
                this.page = 1;
                this.getUser();
              } else {
                this.erroUserNumber = false;
                this.errUserNumberText = res.message;
              }
            });
          }
        }
      },
      // 列表操作 编辑
      editRole(user) {
        this.addTextPopover = "编辑用户";
        this.erroUserName = true;
        this.erroUserNumber = true;
        this.userId = user.userId;
        this.addUserName = user.userName;
        this.addUserNumber = user.loginName;
        this.sex = user.sex + "";
        this.upDatedepName = user.depName;
        this.upDatejobName = user.jobName;
        this.getUnitDeptJob(1);
        this.$refs.refDapPopover.show();
      },

      // 列表操作 功能权限设置
      roleSetting(user) {
        this.userId = user.userId;
        this.$router.push({ path: "/authority/role-setting", query: { userId: this.userId } });
      },

      // 列表操作 删除delUser
      delRole(user) {
        this.userId = user.userId;
        this.$refs.refDelePopover.show();
      },
      // 删除用户按钮
      delBtnFun() {
        this.$refs.refDelePopover.hide();
        delUser(this.userId).then((res) => {
          if (res.code === 0) {
            this.getUser();
          }
        });
      },
      // 列表操作 重置密码
      updatePassword(user) {
        this.userId = user.userId;
        this.updateUserName = user.loginName;
        this.$refs.refupdatePasswordPopover.show();
      },
      // 重置密码按钮
      updateBtnFun() {
        this.$refs.refupdatePasswordPopover.hide();
        updatePwd(this.userId).then((res) => {
          if (res.code === 0) {
            this.$message({
              message: "重置密码成功！",
              center: true,
              type: "success"
            });
          }
        });
      },


      // 切换每页显示多少条事件
      pageSizeChange(val) {
        this.pageSize = val;
        this.getUser();
      },
      // 当前页
      pageCurrentChange(val) {
        this.page = val;
        this.getUser();
      },
      // 头部筛选所属部门
      selectListDept(item) {
        this.searchDeptId = item;
      },
      // 添加部门下拉框
      selectDept(item) {
        this.deptId = item;
      },
      // 添加职位下拉框
      selectJobs(item) {
        this.jobsId = item;
      },
      // 根据值查找所在数组中的下标,返回值元素下标
      getArrIndex(arr, filed, val) {
        return arr.findIndex((item, ind) => {
          if (item[filed] === val) {
            return ind;
          }
        });
      },
      // 管理员禁用自己确定按钮，点击确认跳转登录页；
      disableBtnFun() {
        this.axiosIsRun(1);
      },
      // 管理员禁用自己确定按钮，点击确认跳转登录页；
      closeBtnFun() {
        this.user.isRun = true;
      },
      // 关闭全屏
      closeAll() {
        quitFullScreen();
      }
    },
    beforeRouteLeave (to , from, next){
      if(to.name=='detail'){
        this.isGoOther = false;
      }else{
        this.isGoOther = true;
      }
      next()
    }
  };
</script>
<style scoped>
  * {
    box-sizing: border-box;
  }

  .user-list {
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .authority-content {
    display: flex;
    flex-direction: column;
    margin: 0 30px 30px;
    flex: 1 1 auto;
  }

  .authority-search {
    margin: 30px 0px 20px;
    color: #9b9aad;
  }

  .authority-search .search-title {
    height: 60px;
    display: flex;
    align-items: center;
    font-size: 14px;
    padding-left: 18px;
  }

  .authority-icon {
    width: 18px;
    height: 18px;
    margin-right: 8px;
    vertical-align: middle;
  }

  .authority-search .search-wrapper {
    display: flex;
    align-items: center;
    height: 70px;
    padding-left: 18px;
    border-top: 1px solid #283f59;
  }

  .search-wrapper > li {
    margin-right: 42px;
  }

  /* 表格 */
  .dap-table {
    display: flex;
    flex-direction: column;
    background-color: #1b2b44;
    flex: 1 1 auto;
    border-radius: 4px;
  }

  .table-head {
    font-size: 14px;
    flex: 0 0 60px;
    color: #9b9aad;
    padding: 0 18px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .table-list {
    display: flex;
    flex-direction: column;
    flex: 1 1 auto;
  }

  /* 添加用户弹窗*/
  .add-user-wrapper {
    font-size: 12px;
    width: 400px;
    padding: 30px 30px 0px 26px;
  }

  .add-user-wrapper .add-user-item {
    display: flex;
    align-items: center;
  }

  .add-user-wrapper > li:last-child {
    position: relative;
    z-index: 1;
  }

  .add-user-wrapper .add-text {
    flex: 0 0 68px;
  }

  .add-user-wrapper .dap-input {
    flex: 1 1 auto;
    height: 26px;
  }

  /* 停用后删除按钮 */
  .delBtn {
    color: #e54c77;
  }

  /* 重置密码弹窗 */
  .popover-text {
    text-align: center;
    padding-top: 32px;
    font-weight: normal;
  }
</style>
<style>
  .user-list .tip-text {
    padding-left: 80px;
  }

  /* 下拉框 */
  .user-list .top-text-wrapper, .user-list .drop-down-wrapper {
    width: 200px;
  }

  .user-list .selected-single-filter, .user-list .single-filter-object-show-text, .user-list .left-select-text {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
    text-align: left;
    padding-left: 10px;
  }
</style>

